import {
  Checkpoint_one,
  settings
} from '../checkpoints/checkpoint_one'
import {
  env
} from '../../.eslintrc';
import {
  Setting
} from '../tips/setting'
import {
  Chart
} from '../tips/chart'
import {
  Bag
} from '../tips/bag'
//delete
import {
  CanvasButton
} from '../component/custombutton'

import {
  Rule
} from '../tips/rule'
import {
  playBackgroundMusic,
  pauseBackgroundMusic,
  switchGameBackgroundMusic
} from '../component/music';
import {
  Bubble
} from '../component/bubble'
import {
  ReverseBubble
} from '../component/reverseBubble'
import {
  Activity
} from '../tips/activity';
import { 
  guide 
} from '../tips/guide';
export class DashBoard {
  constructor(canvas,firstlogin = false) {
    // this.canvas = wx.createCanvas();
    this.canvas = canvas;
    this.context = this.canvas.getContext('2d');
    this.width = this.canvas.width;
    this.height = this.canvas.height;
    this.firstlogin = firstlogin;
    this.size_1 = this.width / 12;
    this.size_2 = this.width / 30;
    this.size_3 = this.height / 10;
    this.percentage = 8 / 10;

    this.button = [];

    this.records = wx.getStorageSync('skinInfo');
    this.pigImageCnt = 6

    this.iconSize = this.width * (1 - this.percentage) / 1.5;

    this.userAddress = wx.getStorageSync('province');

    this.topRankX = this.iconSize * 2;
    this.topRankY = this.iconSize / 2;

    this.player_top = this.height / 1.8;
    this.player_bottom = this.height * this.percentage;

    this.rank_top = this.height / 3;
    this.rank_bottom = this.height * this.percentage;

    this.player = {
      x: this.size_1,
      y: this.height * this.percentage,
      width: this.iconSize,
      height: this.iconSize,
      speedY: 3,
      isMovingRight: false
    };

    this.rankWidth = this.width / 3;
    this.rankHeight = this.height * 2 / 3;

    this.currentProvince = wx.getStorageSync('province');
    this.currentRank = null;
    this.allRanks = [];

    this.rankBlocks = [];
    this.distance = this.rankHeight / 4.2;


    this.scrollOffset = 0;
    this.scrollSpeed = 0;

    this.isAnimating = true;

    this.bubble = new Bubble(this.context);
    this.bubbleTime = 0;
    this.maxBubbleSize = 150;

    this.reverseBubble = new ReverseBubble(this.context);

    this.isPopupVisible = false;

    this.pigCount = 9;


    this.direction = 0; //图片播放方向
    this.imageTime = 0; //图片翻转

    wx.showLoading({
      title: '加载中......'
    });

    this.onLoadImage(() => {
      wx.hideLoading();
      this.onLoadDashBoardImage(() => {
        console.log('首页资源加载成功！');
      })
      this.onLoadTipsImage(() => {
        console.log('弹窗资源加载！');
      })
      
      this.init();
    });

  }

  onLoadImage(callback) {
    let loadedCount = 0;
    console.log(this.records)
    const totalImages = 17;

    this.background = wx.createImage();
    this.background.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/background/background_2.png';

    this.enterImage_1 = wx.createImage();
    this.enterImage_1.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/pig_icon_1.png';

    this.enterImage_2 = wx.createImage();
    this.enterImage_2.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/comegame.png';

    this.settingImage = wx.createImage();
    this.settingImage.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/seting.png';

    this.rankImage = wx.createImage();
    this.rankImage.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/chart.png';

    this.BagImage = wx.createImage();
    this.BagImage.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/skinBag.png';

    this.playerImage = wx.createImage();
    this.playerImage.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/playWay.png';

    this.pigImageAdd = 'https://gitee.com/z-l-ya/game-image/raw/master/images/pig';
    this.pigImage = [];
    this.pigImageIndex = 0;

    const checkIfAllLoaded = () => {
      if (loadedCount === totalImages && callback) {
        callback();
      }
    };

    for (let i = 0; i < this.pigImageCnt; i++) {
      const img = wx.createImage();
      img.src = `${this.pigImageAdd}/pig${i + 1}.png`;
      img.onload = () => {
        loadedCount++;
        checkIfAllLoaded();
      };
      this.pigImage.push(img);
    }

    this.icon_pig = wx.createImage();
    this.icon_pig.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/pig1.png';
    this.icon_pig.onload = () => {
      loadedCount++;
      checkIfAllLoaded();
    };

    this.skinImage = [];
    this.skinImageAdd = 'https://gitee.com/z-l-ya/game-image/raw/master/images/skins'

    for (let i = 0; i <= this.pigCount; i++) {
      const img = wx.createImage();
      img.src = `${this.skinImageAdd}/skin_${i + 1}.png`;
      img.onload = () => {
        loadedCount++;
        checkIfAllLoaded();
      };
      this.skinImage.push(img);
    }
  }

  onLoadDashBoardImage(callback) {
    let loadedCount = 0;
    const totalImages = 15 + this.records.length;

    this.activityBackground = wx.createImage();
    this.activityBackground.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/signIn.png'; // 替换为你的背景图片路径
    this.activityBackground.onload = () => {
      loadedCount++;
      checkIfAllLoaded();
    };

    this.gameBackground = wx.createImage();
    this.gameBackground.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/background/background_1.png';
    this.gameBackground.onload = () => {
        loadedCount++;
        checkIfAllLoaded();
    };

    this.wood_image = wx.createImage();
    this.wood_image.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/wood.png';
    this.wood_image.onload = () => {
      loadedCount++;
      checkIfAllLoaded();
    };

    this.pause_icon = wx.createImage();
    this.pause_icon.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/pause.png'
    this.pause_icon.onload = () => {
      loadedCount++;
      checkIfAllLoaded();
    };
    
    //pause.js 4
    this.force_icon = wx.createImage();
    this.force_icon.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/force.png';
    this.force_icon.onload = () => {
      loadedCount++;
      checkIfAllLoaded();
    };

    this.music_icon = wx.createImage();
    this.music_icon.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/music.png';
    this.music_icon.onload = () => {
      loadedCount++;
      checkIfAllLoaded();
    };

    this.open_icon = wx.createImage();
    this.open_icon.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/open.png';
    this.open_icon.onload = () => {
      loadedCount++;
      checkIfAllLoaded();
    };

    this.off_icon = wx.createImage();
    this.off_icon.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/off.png';
    this.off_icon.onload = () => {
      loadedCount++;
      checkIfAllLoaded();
    };

    //rule.js 2
    this.enterImage_1 = wx.createImage();
    this.enterImage_1.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/reback.png';
    this.enterImage_1.onload = () => {
      loadedCount++;
      checkIfAllLoaded();
    };

    this.enterImage_2 = wx.createImage();
    this.enterImage_2.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/contactService.png';
    this.enterImage_2.onload = () => {
      loadedCount++;
      checkIfAllLoaded();
    };

    //checkpoint_two.js 6
    this.pig = wx.createImage();
    this.currentSkinImage = wx.getStorageSync('currentSkinImage');
    this.pig.src = `${this.currentSkinImage}`;
    this.pig.onload = () => {
      loadedCount++;
      checkIfAllLoaded();
    };

    this.prop1_icon = wx.createImage();
    this.prop1_icon.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/prop1.png'
    this.prop1_icon.onload = () => {
      loadedCount++;
      checkIfAllLoaded();
    };

    this.prop2_icon = wx.createImage();
    this.prop2_icon.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/prop2.png'
    this.prop2_icon.onload = () => {
      loadedCount++;
      checkIfAllLoaded();
    };

    this.prop3_icon = wx.createImage();
    this.prop3_icon.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/prop3.png'
    this.prop3_icon.onload = () => {
      loadedCount++;
      checkIfAllLoaded();
    };

    this.time_icon = wx.createImage();
    this.time_icon.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/time.png'
    this.time_icon.onload = () => {
      loadedCount++;
      checkIfAllLoaded();
    };

    //bag.js this.records.length
    this.skinBagImage = [];
    const loadImage = (record, index) => {
      const img = wx.createImage();
      img.src = record.skinUrl;
      img.onload = () => {
        this.skinBagImage[index] = img;
        loadedCount++;
        checkIfAllLoaded();
      };
      img.onerror = () => {
        loadedCount++;
        checkIfAllLoaded();
      };
    };

    this.totalSkins = this.records.length;
    this.records.forEach((record, index) => {
      if (record.haveStatus === true) {
        loadImage(record, index);
      } else {
        const img = wx.createImage();
        img.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/skins/skin_black.png';
        img.onload = () => {
          this.skinBagImage[index] = img;
          loadedCount++;
          checkIfAllLoaded();
        };
      }
    });

    const checkIfAllLoaded = () => {
      if (loadedCount === totalImages && callback) {
        callback();
      }
    };
  }

  onLoadTipsImage(callback) {
    let loadedCount = 0;
    const totalImages = 29;
    
    //lose.js 22
    this.loseBackground = wx.createImage();
    this.loseBackground.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/background/background_3.png';
    this.loseBackground.onload = () => {
      loadedCount++;
      checkIfAllLoaded();
    };

    this.tree_background = wx.createImage();
    this.tree_background.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/tree_icon_1.png';
    this.tree_background.onload = () => {
      loadedCount++;
      checkIfAllLoaded();
    };


    this.losePigImageAdd = 'https://gitee.com/z-l-ya/game-image/raw/master/images/pig'
    this.losePigImageCnt = 20
    this.losePigImage = [];

    for (let i = 0; i < this.losePigImageCnt; i++) {
      const img = wx.createImage();
      img.src = `${this.losePigImageAdd}/pig_${i + 1}.png`;
      img.onload = () => {
        loadedCount++;
        checkIfAllLoaded();
      };
      this.losePigImage.push(img);
    }

    //cancel.js 4
    this.iron_image = wx.createImage();
    this.iron_image.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/iron.png';
    this.iron_image.onload = () => {
      loadedCount++;
      checkIfAllLoaded();
    };

    this.rebackImage = wx.createImage();
    this.rebackImage.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/rebackGame.png';
    this.rebackImage.onload = () => {
      loadedCount++;
      checkIfAllLoaded();
    };

    this.watchAdImage = wx.createImage();
    this.watchAdImage.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/watchAd.png';
    this.watchAdImage.onload = () => {
      loadedCount++;
      checkIfAllLoaded();
    };

    //downGrade.js 1
    this.gold_image = wx.createImage();
    this.gold_image.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/gold.png';
    this.gold_image.onload = () => {
      loadedCount++;
      checkIfAllLoaded();
    };

    //win.js 3
    this.loseBackground_image = wx.createImage();
    this.loseBackground_image.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/background/background_1.png';
    this.loseBackground_image.onload = () => {
      loadedCount++;
      checkIfAllLoaded();
    };

    this.pig_background_2 = wx.createImage();
    this.pig_background_2.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/pig2.png';
    this.pig_background_2.onload = () => {
      loadedCount++;
      checkIfAllLoaded();
    };
    this.shareImage = wx.createImage();
    this.shareImage.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/share.png';
    this.shareImage.onload = () => {
      loadedCount++;
      checkIfAllLoaded();
    };

    const checkIfAllLoaded = () => {
      if (loadedCount === totalImages && callback) {
        callback();
      }
    };

  }

  init() {
    this.getSkinsInfo();
    pauseBackgroundMusic();
    if (settings.MUSIC_OPEN === true) {
      playBackgroundMusic();
    }
    this.getRankCount(() => {
      // 皮肤随机
      this.rankBlocks.forEach(b => {
        for (let i = 0; i < 9; i++) {
          b.index[i] = Math.floor(Math.random() * 10);
        }
      });
      setTimeout(()=>{
        if(this.firstlogin){
          console.log("guid");
          wx.offTouchStart();
          this.isAnimating = false;
          this.buttonHide();
          this.gameClubButton.hide();
          var guid = new guide(this.canvas, this.width, this.height,this.continueRebackGame.bind(this));
        }
      },50);
      console.log('init');
      this.getsignIn();
      this.draw();
    });
    wx.onTouchStart((event) => this.onTouchStart(event));
    wx.onTouchMove((event) => this.onTouchMove(event));
    wx.onTouchEnd(() => this.onTouchEnd());
  }

  draw() {
    this.drawAnimate();
    this.createButton();
  }

  getRankCount(callback) {
    // 后期访问量过大是否需要增加缓存处理？？？避免访问过多导致性能降低
    wx.cloud.init({
      "env": 'prod-8gf88ck5bb3ddd38'
    })
    wx.cloud.callContainer({
      "config": {
        "env": "prod-8gf88ck5bb3ddd38"
      },
      "path": `/apis/countRanks/selectRankCounts`,
      "method": 'GET',
      "header": {
        'content-type': 'application/json',
        'AuthToken': wx.getStorageSync("AuthToken"),
        "X-WX-SERVICE": env.service,
      },
      success: ({
        statusCode,
        header,
        data
      }) => {
        console.log(data);
        this.allRanks = data.data.map(item => {
          if (item.province === this.currentProvince) {
            this.currentRank = item.rank;
          }
          return {
            province: item.province,
            count: item.count,
            rank: item.rank
          };
        }).sort((a, b) => a.rank - b.rank);
        // 存入排行
        for (let i = 0; i < this.allRanks.length; i++) {
          this.rankBlocks.push({
            provinceName: this.allRanks[i].province,
            completeCount: this.allRanks[i].count,
            x: this.width * 2 / 3,
            y: this.rank_top + this.iconSize * i,
            width: this.iconSize * 2,
            height: this.iconSize,
            distance: this.distance,
            index: []
          });
        }
        callback();
      },
      fail: console.warn,
    });
  }

  getSkinsInfo() {
    wx.cloud.callContainer({
      "config": {
        "env": "prod-8gf88ck5bb3ddd38"
      },
      "path": `/apis/skin/selectUserSkins`,
      "header": {
        'content-type': 'application/json',
        'AuthToken': wx.getStorageSync("AuthToken"),
        "X-WX-SERVICE": env.service
      },
      "method": "GET",
      success: (res) => {
        console.log(res.data.skinInfo);
        wx.setStorage({
          key: 'skinInfo',
          data: res.data.skinInfo,
          success: function (res) {
            console.log('skin success');
          },
          fail: function (err) {
            console.error('skin seccess', err);
          }
        });
      },
      fail: console.warn,
    })
  }

  drawAnimate() {
    if (this.isAnimating) {
      this.context.clearRect(0, 0, this.width, this.height);

      this.context.drawImage(this.background, 0, 0, this.width, this.height);
      this.drawBubbleText();
      this.drawTopRank();
      this.drawPigMove();

      if (!this.isScrolling) {
        this.scrollSpeed *= 0.95;
        this.scrollOffset += this.scrollSpeed;
        this.scrollOffset = Math.min(0, this.scrollOffset);
        const maxOffset = -((this.rankBlocks.length * this.distance) - (this.height - this.rank_bottom));
        this.scrollOffset = Math.max(maxOffset, this.scrollOffset);


        if (isNaN(this.scrollSpeed)) {
          this.scrollSpeed = 0;
          // console.error("scrollSpeed is NaN, resetting to 0");
        }
        if (isNaN(this.scrollOffset)) {
          this.scrollOffset = 0;
          // console.error("scrollOffset is NaN, resetting to 0");
        }
      }
      this.drawWoodRank();

    }
    requestAnimationFrame(this.drawAnimate.bind(this));
  }

  onTouchStart(event) {
    if (event.touches && event.touches[0]) {
      this.touchStartY = event.touches[0].clientY;
      this.isScrolling = true;
      this.scrollSpeed = 0;
    } else {
      console.warn("TouchStart event does not have touches[0]");
    }
  }

  onTouchMove(event) {
    if (event.touches && event.touches[0]) {
      const touchY = event.touches[0].clientY;
      const deltaY = touchY - this.touchStartY;
      this.touchStartY = touchY;
      this.scrollOffset += deltaY;

      // 限制滚动范围
      this.scrollOffset = Math.min(0, this.scrollOffset); // 不允许向下超出顶部
      const maxOffset = -((this.rankBlocks.length * this.distance) - (this.height - this.rank_bottom));
      this.scrollOffset = Math.max(maxOffset, this.scrollOffset); // 不允许向上超出底部
      this.scrollSpeed = deltaY;
    } else {
      console.warn("TouchMove event does not have touches[0]");
    }
  }

  onTouchEnd() {
    this.isScrolling = false;
  }

  drawWoodRank() {
    const rank_X = this.width / 2 - this.size_1;
    const rank_Y = this.height / 3;
    const rank_width = this.rankWidth + this.size_1 * 2;
    const rank_height = this.rankHeight - this.size_1 * 4;

    // 是否需要使用第二画布防止背景清空, todo
    // this.context.clearRect(rank_X, rank_Y, rank_width, rank_height); 
    // this.context.fillStyle = 'pink';
    // this.context.fillRect(rank_X, rank_Y, rank_width, rank_height);

    const provinceRankX = rank_X + rank_width / 2;

    const smallPigX = rank_X;

    let startY = rank_Y + this.scrollOffset;
    this.rankBlocks.forEach((block, index) => {
      if (startY >= rank_Y && startY <= rank_Y + rank_height - block.distance) { // 只绘制在可见区域内的记录
        // this.context.fillStyle = 'green';
        // this.context.fillRect(rank_X, startY, rank_width, 30);
        this.context.font = `${this.size_2}px Arial`;
        this.context.fillStyle = 'black';
        this.context.textAlign = 'center';
        // 绘制排名
        this.context.fillText(`${block.provinceName} 第${index + 1}名`, provinceRankX, startY + this.size_2);
        // 绘制通关次数
        this.context.fillText(`总次数:${block.completeCount}`, provinceRankX, startY + this.size_2 * 2);
        for (let i = 0, j = 1, k = 0; i < this.pigCount; i++, j++) {
          if (smallPigX + j * this.size_2 * 3 > smallPigX + rank_width - this.iconSize) {
            j = 1;
            k += 2;
          }
          if (this.imageTime < 1000) {
            this.context.drawImage(this.skinImage[block.index[i]], smallPigX + j * this.size_2 * 3, startY + (1.5 + k) * this.size_2, this.iconSize, this.iconSize);
            this.imageTime += 1;
          } else if (this.imageTime < 2000) {
            this.context.save();

            this.context.translate(smallPigX + j * this.size_2 * 3 + this.iconSize, 0);
            this.context.scale(-1, 1);

            this.context.drawImage(this.skinImage[block.index[i]], 0, startY + (1.5 + k) * this.size_2, this.iconSize, this.iconSize);

            this.context.restore();
            this.imageTime += 1;
          } else {
            this.imageTime = 0;
          }

        }
      }
      startY += block.distance;
    })
  }

  drawPigMove() {
    // 更新玩家位置
    if (!this.player.isMovingRight) {
      this.player.y += this.player.speedY;
      if (this.player.y > this.player_bottom || this.player.y < this.player_top) {
        this.player.speedY = -this.player.speedY;
      }
    } else {
      this.player.x += 5;
      if (this.player.x >= this.width) //不能出手机边界
      {
        this.player.x = this.size_1;
        this.player.y = this.height * this.percentage;
        this.player.isMovingRight = false;
      }
    }
    if (this.bubbleTime > 100 && this.bubbleTime < 250) {
      this.bubble.drawBubble("我也想登顶~", this.player.x + this.iconSize, this.player.y, this.maxBubbleSize);
    } else if (this.bubbleTime > 300 && this.bubbleTime < 450) {
      this.bubble.drawBubble("带我去玩叭~", this.player.x + this.iconSize, this.player.y, this.maxBubbleSize);
    } else if (this.bubbleTime > 500) {
      this.bubbleTime = 0;
    }
    this.bubbleTime += 1;
    this.context.drawImage(this.icon_pig, this.player.x, this.player.y, this.iconSize, this.iconSize);
  }

  drawTopRank() {
    this.pigImageIndex = (this.pigImageIndex + 1) % (this.pigImageCnt * 2);
    if (this.pigImageIndex > 5) {
      this.direction = this.pigImageCnt * 2 - this.pigImageIndex;
      this.context.drawImage(this.pigImage[this.direction - 1], this.topRankX, this.topRankY, this.iconSize * 3, this.iconSize * 3);
    } else {
      this.context.drawImage(this.pigImage[this.pigImageIndex], this.topRankX, this.topRankY, this.iconSize * 3, this.iconSize * 3);
    }

    const province = wx.getStorageSync("province");

    this.context.font = `${this.size_2}px Arial`;
    this.context.fillStyle = 'pink';
    this.context.textAlign = 'center';
    this.context.fillText(province, this.topRankX + this.size_1, this.topRankY + this.iconSize * 2 + this.size_2);
    this.context.fillText(`全国第${this.currentRank}名`, this.topRankX + this.size_1 + this.size_2 * 5, this.topRankY + this.iconSize * 2 + this.size_2);
  }

  drawBubbleText() {
    this.context.font = `italic ${this.size_1 / 2}px Arial`;
    this.context.fillStyle = 'black';
    this.context.textAlign = 'left';
    this.context.fillText('排行榜', this.size_1, this.height * this.percentage + this.size_1 * 4);

    this.context.fillText('设置', this.iconSize * 3 / 4, this.iconSize * 2 + this.size_1 * 2);

    this.context.fillText('背包', this.width * this.percentage - this.size_1 * 1 / 2, this.height * this.percentage + this.size_1 * 4);

    this.context.fillText('玩法', this.iconSize * 3 / 4, this.iconSize * 5 / 3);
  }

  createButton() {
    let _this = this;
    this.enter_1 = {
      type: "image",
      image: "https://gitee.com/z-l-ya/game-image/raw/master/images/icons/pig_icon_1.png",
      style: {
        backgroundColor: 'transparent',
        left: this.width / 2.4,
        top: this.height * this.percentage + this.size_1,
        width: this.width / 6,
        height: this.size_1,
        textAlign: 'center',
        textColor: "black",
        borderRadius: 10
      },
      success(button) {
        console.log('创建成功')
        console.log(_this.enter_1.style.left, _this.enter_1.style.top, _this.enter_1.style.width, _this.enter_1.style.height)
        _this.button.push(button);
        button.drawButton(_this.context); // 绘制按钮
        button.onTap((res) => {
          if (_this.isPopupVisible) return;
          _this.isAnimating = false;
          _this.buttonDestory();
          _this.gameClubButton.hide();
          _this.canvas.width = _this.canvas.width;
          const one = new Checkpoint_one(_this.canvas);
        })
      }
    };

    this.enter_2 = {
      type: "image",
      image: "https://gitee.com/z-l-ya/game-image/raw/master/images/icons/comegame.png",
      style: {
        backgroundColor: 'transparent',
        left: this.width / 3,
        top: this.height * this.percentage + this.size_1 * 2,
        width: this.width / 3,
        height: this.size_1 * 1.5,
        textAlign: 'center',
        textColor: "black",
        borderRadius: 10
      },
      success(button) {
        _this.button.push(button);
        button.drawButton(_this.context); // 绘制按钮
        button.onTap((res) => {
          if (_this.isPopupVisible) return;
          _this.isAnimating = false;
          _this.buttonDestory();
          _this.gameClubButton.hide();
          _this.canvas.width = _this.canvas.width;
          const one = new Checkpoint_one(_this.canvas); //修改
        })
      },
    };
    this.rank = {
      type: "image",
      image: "https://gitee.com/z-l-ya/game-image/raw/master/images/icons/chart.png",
      style: {
        backgroundColor: 'transparent',
        left: this.size_1,
        top: this.height * this.percentage + this.size_1 * 2,
        width: this.iconSize,
        height: this.iconSize,
        borderRadius: 10
      },
      success(button) {
        _this.button.push(button);
        button.drawButton(_this.context); // 绘制按钮
        button.onTap((res) => {
          if (_this.isPopupVisible) return;
          _this.isAnimating = false;
          _this.buttonHide();
          _this.gameClubButton.hide();
          let chartPopup = new Chart(_this.canvas, _this.width, _this.height, _this.continueRebackGame.bind(_this));
          chartPopup.drawPopup();
        })
      },
    };
    this.setting = {
      type: "image",
      image: "https://gitee.com/z-l-ya/game-image/raw/master/images/icons/seting.png",
      style: {
        backgroundColor: 'transparent',
        left: this.size_1,
        top: this.iconSize * 2,
        width: this.iconSize,
        height: this.iconSize,
        borderRadius: 10
      },
      success(button) {
        _this.button.push(button);
        button.drawButton(_this.context); // 绘制按钮
        button.onTap((res) => {
          if (_this.isPopupVisible) return;
          _this.isAnimating = false;
          _this.isPopupVisible = true;
          _this.buttonHide();
          _this.gameClubButton.hide();
          let settingPopup = new Setting(_this.canvas, _this.width, _this.height, () => {
            _this.isPopupVisible = false;
            _this.continueRebackGame();
          });
          settingPopup.drawPopup();
        })
      },
    };
    this.Bag = {
      type: "image",
      image: "https://gitee.com/z-l-ya/game-image/raw/master/images/icons/skinBag.png",
      style: {
        backgroundColor: 'transparent',
        left: this.width * this.percentage - this.size_1 * 1 / 2,
        top: this.height * this.percentage + this.size_1 * 2,
        width: this.iconSize,
        height: this.iconSize,
        borderRadius: 10
      },
      success(button) {
        _this.button.push(button);
        button.drawButton(_this.context); // 绘制按钮
        button.onTap((res) => {
          if (_this.isPopupVisible) return;
          _this.isAnimating = false;
          _this.isPopupVisible = true;
          _this.buttonHide();
          _this.gameClubButton.hide();
          let bagPopup = new Bag(_this.canvas, _this.width, _this.height, () => {
            _this.isPopupVisible = false; // 弹窗关闭时重置标志
            _this.continueRebackGame();
          });
        })
      },
    };
    this.playWay = {
      type: "image",
      image: "https://gitee.com/z-l-ya/game-image/raw/master/images/icons/playWay.png",
      style: {
        backgroundColor: 'transparent',
        left: this.size_1,
        top: this.iconSize / 2,
        width: this.iconSize,
        height: this.iconSize,
      },
      success(button) {
        _this.button.push(button);
        button.drawButton(_this.context); // 绘制按钮
        button.onTap((res) => {
          _this.gameClubButton.hide();
          if (_this.isPopupVisible) return; // 如果有弹窗显示，忽略点击事件
          _this.isAnimating = false;
          _this.isPopupVisible = true;
          _this.buttonHide();
          let rulePopup = new Rule(_this.canvas, _this.width, _this.height, () => {
            _this.isPopupVisible = false; // 弹窗关闭时重置标志
            _this.continueRebackGame();
          });
        })
      },
    };
    this.activity = {
      type: "image",
      image: "https://gitee.com/z-l-ya/game-image/raw/master/images/icons/activity.png",
      style: {
        backgroundColor: 'transparent',
        left: this.size_1,
        top: this.iconSize * 7 / 2,
        width: this.iconSize,
        height: this.iconSize,
      },
      success(button) {
        _this.button.push(button);
        button.drawButton(_this.context); // 绘制按钮
        button.onTap((res) => {
          _this.gameClubButton.hide();
          if (_this.isPopupVisible) return; // 如果有弹窗显示，忽略点击事件
          _this.isAnimating = false;
          _this.isPopupVisible = true;
          _this.buttonHide();
          let activityPopup = new Activity(_this.canvas, _this.width, _this.height, () => {
            _this.isPopupVisible = false; // 弹窗关闭时重置标志
            _this.continueRebackGame();
          });
        })
      },
    };
    new CanvasButton(this.enter_1);
    new CanvasButton(this.enter_2);
    new CanvasButton(this.rank);
    new CanvasButton(this.setting);
    new CanvasButton(this.Bag);
    new CanvasButton(this.playWay);
    new CanvasButton(this.activity);

    this.gameClubButton = wx.createGameClubButton({
      icon: 'green',
      style: {
        left: this.size_1,
        top: this.iconSize * 5,
        width: this.iconSize * 4 / 5,
        height: this.iconSize * 4 / 5
      },
      openlink: 'L_Gh_YCqH3LnfXgrzNDNW3XQCN1kNWo23ijAfozpBvJ86ImPjJnqbA3_27zf2UFzUt_vXXtDncPppuDNbHXddG7npUzx4jUVOmmEFFJKdskp9QYpulTk6jTC4W53wwVzy'
    })
  }

  continueRebackGame() {
    this.isAnimating = true;
    this.buttonShow();
    // this.createButton();
    // wx.showLoading({
    //   title: '加载中......'
    // });

    // this.onLoadImage(() => {
    //   wx.hideLoading();
    //   this.init();
    // });

  }

  getsignIn() {
    wx.cloud.init({
      env: 'prod-8gf88ck5bb3ddd38'
    })
    wx.cloud.callContainer({
      "config": {
        "env": "prod-8gf88ck5bb3ddd38"
      },
      "path": "/apis/sign/signIndays",
      "header": {
        'content-type': 'application/json',
        'AuthToken': wx.getStorageSync("AuthToken"),
        "X-WX-SERVICE": env.service
      },
      "method": "GET",
      success: (res) => {
        console.log(res);
        this.nowDay = res.data.signIndays;
        this.signIn = res.data.todayIsSigned;
        wx.setStorageSync('nowDay', this.nowDay);
        wx.setStorageSync('signIn', this.signIn);
      },
      fail: console.warn,
    })
  }

  buttonDestory() {
    this.button.forEach(bt => {
      bt.destroy();
    });
    // this.button = null;
  }

  buttonHide() {
    this.button.forEach(bt => {
      bt.hideButton();
    });
    // this.button = null;
  }
  buttonShow() {
    this.button.forEach(bt => {
      bt.showButton();
    });
    this.gameClubButton.show();
  }

}